package main

import (
	"context"
	"flag"
	"os"
	"os/signal"
	"syscall"

	"github.com/nosch/smtpoll/config"
	"github.com/nosch/smtpoll/logger"
	"github.com/nosch/smtpoll/smtpserver"
)

func main() {
	// 解析命令行参数
	configPath := flag.String("config", "config.yaml", "Path to config file")
	flag.Parse()

	// 加载配置
	config, err := config.LoadConfig(*configPath)
	if err != nil {
		logger.LogError(context.Background(), "Failed to load config", "error", err)
		os.Exit(1)
	}

	// 创建消息处理器
	handler := smtpserver.NewDefaultMessageHandler("received_mails")

	// 创建服务器选项
	options := &smtpserver.ServerOptions{
		Host:         config.Server.Host,
		Ports:        config.Server.Ports,
		ReadTimeout:  config.Server.ReadTimeout,
		WriteTimeout: config.Server.WriteTimeout,
		MaxConn:      config.Server.MaxConn,
		NetworkLib:   config.Server.NetworkLib,
	}

	// 根据配置选择服务器实现
	var server smtpserver.Server
	switch config.Server.NetworkLib {
	case "netpoll":
		server = smtpserver.NewNetpollServer(options, handler)
	case "gnet":
		server = smtpserver.NewGnetSmtpServer(options, handler)
	case "net":
		server = smtpserver.NewNetServer(options, handler)
	default:
		logger.LogError(context.Background(), "Unsupported network library", "library", config.Server.NetworkLib)
		os.Exit(1)
	}

	// 启动服务器
	if err := server.Run(); err != nil {
		logger.LogError(context.Background(), "Server failed to run", "error", err)
		os.Exit(1)
	}

	// 等待中断信号
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	// 优雅关闭
	logger.LogInfo(context.Background(), "Shutting down server...")
	server.Stop()
}
